package com.ambulance.project.gen.util;

import com.ambulance.common.exception.CustomException;
import com.ambulance.project.gen.domain.GenTable;
import com.ambulance.project.gen.domain.GenTableColumn;
import com.ambulance.project.gen.mapper.GenTableColumnMapper;
import com.ambulance.project.gen.mapper.GenTableMapper;
import com.ambulance.utils.CommonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/***
 *  @description
 *  @author zhao
 *  @date: 2020/5/11
 *  @version: v1.0
 */
@Component
public class VueCustomerUtils {

    @Autowired
    private GenTableColumnMapper genTableColumnMapper;

    @Autowired
    private GenTableMapper genTableMapper;

    /**
     * 自定义导入生成代码的数据
     *
     * @param name
     * @param common
     * @param fields
     */
    public void doImport(String name, String common, List<GenTableColumn> fields) {
        GenTable genTable = genTableMapper.selectGenTableByName(name);
        if (CommonUtils.checkNull(genTable)) {
            genTable = new GenTable();
            genTable.setTableName(name);
            genTable.setTableComment(common);
            GenUtils.initTable(genTable, "zr");
            int row = genTableMapper.insertGenTable(genTable);
            if (!(row > 0)) {
                throw new CustomException("插入数据失败");
            }
        }
        doImportCol(genTable, fields);


    }

    private void doImportCol(GenTable genTable, List<GenTableColumn> fields) {

        if (fields.isEmpty()) {
            return;
        }
        if (CommonUtils.checkNull(genTable)) {
            return;
        }

        for (GenTableColumn column : fields) {
            column.setTableId(genTable.getTableId());
            //添加自定义列到某个表中
            column.setColumnType("varchar(128)");
            column.setCreateBy(genTable.getCreateBy());
            try {
                //设置表的属性赋值给列属性
                GenUtils.customerColumnField(column, genTable);
                GenTableColumn tableColumn = genTableColumnMapper.selectGenTableColumnListByTableIdAndCol(genTable.getTableId(), column.getColumnName());
                //若该列没有则生成
                if (CommonUtils.checkNull(tableColumn)) {
                    genTableColumnMapper.insertGenTableColumn(column);
                }
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            }

        }


    }


}
